<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Shop\Api;
use Admin\Api\DatatreeApi;
use \Common\Api\Api;
use Shop\Model\ProductAttrModel;
use Shop\Model\ProductGroupModel;
use Shop\Model\ProductImageModel;
use \Shop\Model\ProductModel;
use Shop\Model\ProductPropModel;
use Think\Page;

class ProductApi extends Api{

    /**
     *
     * 查询商品包含的所有国家信息
     */
    const QUERY_ALL_COUNTRY = "Shop/Product/queryAllCountry";

    /**
     *
     * 查询商品信息根据用户ID
     */
    const QUERY_WITH_STORE_UID = "Shop/Product/queryWithStoreUID";
    /**
     * 查询商品信息根据分组
     */
    const QUERY_BY_GROUP = "Shop/Product/queryByGroup";
    /**
     * 查询商品信息并包含店铺信息
     */
    const QUERY_WITH_STORE = "Shop/Product/queryWithStore";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/Product/queryNoPaging";
    /**
     * 查询 不分页 已上架 未删除
     */
    const QUERY_NO_PAGING_ON_SHELF = "Shop/Product/queryNoPagingOnShelf";
    /**
     * 查询 已上架 未删除
     */
    const QUERY_ON_SHELF = "Shop/Product/queryOnShelf";
    /**
     * 添加
     */
    const ADD = "Shop/Product/add";

    /*
     * 简单的添加商品信息
     * */
    const ZADD = "Shop/Product/zadd";
    /**
     * 保存
     */
    const SAVE = "Shop/Product/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/Product/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/Product/delete";
    /**
     * 删除
     */
    const PRETEND_DELETE = "Shop/Product/pretendDelete";

    /**
     * 查询
     */
    const QUERY = "Shop/Product/query";
    /**
     * 查询所有图片信息
     */
    const ALLQUERY = "Shop/Product/allquery";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/Product/getInfo";

	const COUNT="Shop/Product/count";

    //减少库存
    const SET_DEC="Shop/Product/setDec";
    //增加库存
    const SET_INC="Shop/Product/setInc";

    const QUERY_WITH_COUNT="Shop/Product/queryWithCount";

    const QUERY_WITH_COUNT_JOIN_CATE ="Shop/Product/queryWithCountJoinCate";


    /**
     * 获取商品详情信息
     */
    const DETAIL="Shop/Product/detail";
    /**
     * 获取商品信息，随机10条
     */
    const RANDOM_QUERY="Shop/Product/randomQuery";

    /**
     * 批量上下架
     */
    const SHELF_ALL = "Shop/Product/shelfAll";

    /*
 * 查询卖出的所有商品的订单信息
 * */
    const SELECT_SELL_ORDER = "Shop/Product/selectSellOrder";
    /*
    *分页调出所有商品信息
    * */
    const PAGE_ALL_PRODUCT = "Shop/Product/page_all_product";

    /*
     * 分页将商品和发布者的信息一起发送出来
     * */
    const PRODUCT_WXUSER = "Shop/Product/product_wxuser";

    protected function _init(){
		$this->model = new ProductModel();
	}

    public function shelfAll($onshelf,$ids){

        $this -> model -> startTrans();

        $error = false;
        foreach($ids as $k => $v){
            $map = array('id'=>$v);
            $entity = array('onshelf'=>$onshelf);
            $result = $this -> model -> create($entity, 2);
            if($result === false){
                $error = $this -> model -> getError();
            }
            $result = $this -> model -> where($map) -> save();
            if ($result === false) {
                $error = $this -> model -> getDbError();
            }
        }
        if($error === false){
            $this -> model -> commit();
            return $this -> apiReturnSuc("上架成功");
        }else{
            $this -> model -> rollback();
            return $this -> apiReturnErr($error);
        }
    }

    /**
     * query
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function query($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $query = $this->model;

        $main_img_type = 6015;//主图

        $query = $query -> join('(select * from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left');

        if(!is_null($map)){
            $map['status'] = 1;

            $query = $query->where($map);
        }

        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }

    /**
     * allquery调出所有图片
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function allquery($map = null, $page = array('curpage'=>0,'size'=>20), $order = false, $params = false, $fields = false,$group = false) {
        $query = $this->model;
        if(false==$group){
            $query = $query -> join('(select * from itboye_product_image ) as image on id=image.pid','left') ;
        }elseif($group==true){
            $query = $query -> join('(select * from itboye_product_image ) as image on (id=image.pid)','left') ;
        }else{
            $this->apiReturnErr("操作出错");
        }
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){

            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();
        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }


    public function queryOnShelf($map = null,$page = array('curpage'=>0,'size'=>10),$order = false, $params = false, $fields = false){
        $query = $this -> model;

        $query = $query -> page($page['curpage'] . ',' . $page['size']);

        if($order !== false){

            $query = $query -> order($order);
        }
        if($fields !== false){
            $query = $query -> field($fields);
        }
        $map['status'] = 1;
        $map['onshelf'] = 1;
        $list = $query -> where($map) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();

        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("count" => $count,"show" => $show,"list" => $list));

    }

    public function queryNoPagingOnShelf($map = null,$order = false){
        $query = $this->model;

        $main_img_type = 6015;//主图

        $query = $query -> join('(select * from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left');

        $map['status'] = 1;
        $map['onshelf'] = 1;

        $query = $query->where($map);

        if(!($order === false)){
            $query = $query -> order($order);
        }

        $result = $query -> select();

        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        return $this -> apiReturnSuc($result);
    }


    /**
     * query
     * @param 查询条件|null $map
     * @param array|分页参数 $page
     * @param bool|排序参数 $order
     * @param bool|点击分页时带参数 $params
     * @param bool $fields
     * @return array
     * @internal param 查询条件 $map
     * @internal param 分页参数 $page
     * @internal param 排序参数 $order
     * @internal param 点击分页时带参数 $params
     */
    public function queryWithCount($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $query = $this->model;

        $main_img_type = 6015;//主图

        $query = $query -> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left')
            -> join('(select min(price) as price,product_id from itboye_product_sku group by product_id) as sku on id=sku.product_id','inner')
            -> join('itboye_product_attr on id=itboye_product_attr.pid','left');

        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model-> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left') -> join('(select min(price) as price,product_id from itboye_product_sku group by product_id) as sku on id=sku.product_id','inner') -> join('itboye_product_attr on id=itboye_product_attr.pid','left') -> where($map) -> count();

        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        $show = $Page -> show();


        return $this -> apiReturnSuc(array("count" => $count, "list" => $list));
    }

    /**
     * 从商品里随机返回10个商品
     */
    public function randomQuery(){

        $count = $this->model->where(array('status'=>1,'onshelf'=>ProductModel::STATUS_ONSHELF))->count();
        if($count < 6) {

            $result = $this->model->field('id,name,price,ori_price,main_img')->where(array('status'=>1,'onshelf'=>ProductModel::STATUS_ONSHELF))->select();

        }else{

            $rand  = mt_rand(0,$count-6); //产生随机数。

            $limit = $rand.','.'6';

            $result = $this->model->field('id,name,price,ori_price,main_img')->where(array('status'=>1,'onshelf'=>ProductModel::STATUS_ONSHELF))->limit($limit)->select();
        }

        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }

        return $this->apiReturnSuc($result);

    }

    public function detail($id){

        $map = array('id'=>$id);
        $result= $this->getInfo($map);
        if(!$result['status']){
            return $result;
        }

        $product = $result['info'];
        $product['_price']  = $product['price'];

        //获取商品信息
        $result = apiCall(ProductAttrApi::GET_INFO, array( array('pid' => $id)));

        if (!$result['status']) {
            return $result;
        }


        $product_attr = $result['info'];
        if(is_null($product_attr)){
            return $this->apiReturnErr("商品信息有误!");
        }

        //获取商品图片
        $main_img_type = 6015;
        $show_img_type = 6016;

        $result = apiCall(ProductImageApi::QUERY_NO_PAGING,array(array('pid' => $id)));

        if(!$result['status']){
            return $result;
        }

        $main_img = "";
        $img = "";
        foreach($result['info'] as $vo){
            if($vo['type'] == $main_img_type){
                $main_img = $vo['img_id'];
            }else if($vo['type'] == $show_img_type){
                $img = $img.$vo['img_id'].',';
            }
        }
        $imgs = explode(",",$img);
        array_pop($imgs);
        $product_img = array(
            'main_img' => $main_img,
            'imgs' => $imgs,
        );

        /*//获取规格
        $skuItemList = array();
        $skuInfo = array();

        if($product['has_sku']!=0){

            $map=array(
                'product_id'=>$id,
            );

            $result=apiCall(ProductSkuApi::QUERY_NO_PAGING,array($map));

            if (!$result['status']) {
                return $result;
            }

            $skuItemList = $result['info'];

            $result = apiCall(SkuApi::QUERY_SKU_TABLE,array($product['cate_id']));

            $skuInfo = $result['info'];

        }

        $product['sku_list']=$skuItemList;
        $product['sku_info_list']=$skuInfo;*/
        $product = array_merge($product,$product_attr,$product_img);

        /*$result = apiCall(ProductGroupApi::GET_INFO,array(array('p_id'=>$id,'start_time'=>array('LT',time())),"price ASC"));

        $product['is_time_limit'] = 0;
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }elseif(is_array($result['info'])){
            $product['is_time_limit'] = 1;
            $product['price'] = $result['info']['price'];
            $product['price_begin_time'] = $result['info']['start_time'];
            $product['price_end_time'] = $result['info']['end_time'];
        }
        $map  = array(
           'code' =>$product['dt_tariff_code'],
        );
        $result = apiCall(CategoryApi::GET_INFO,array(array($map)));
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }elseif(is_array($result['info'])) {
            $product['tax_rate'] = $result['info']['taxrate'];
            $product['cate_name'] = $result['info']['name'];
        }*/

        return $this->apiReturnSuc($product);
    }


    /**
     * 查询商品包含的所有国家信息
     * @return array
     */
    public function queryAllCountry(){
        $result = $this->model->distinct(true)->field('dt_origin_country')->select();
        if($result === false){
            $error = $this -> model -> getError();
            return $this->apiReturnErr($error);
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    /**
     * 商品用id保存(product,product_attr,product_image)
     * @param $id
     * @param $entity
     */
    public function saveByID( $id , $entity ){
        $attr_entity = array(
            'has_receipt' => $entity['has_receipt'],
            'under_guaranty' => $entity['under_guaranty'],
            'support_replace' => $entity['support_replace'],
            'total_sales' => $entity['total_sales'],
            'buy_limit' => $entity['buy_limit'],
        );
        $img = $entity['img'];

        $properties = false;
        if(isset($entity['properties']) && count(json_decode($entity['properties'])) != 0){
            $properties = $entity['properties'];
        }

        $group = $entity['group'];

        unset($entity['id']);
        unset($entity['has_receipt']);
        unset($entity['under_guaranty']);
        unset($entity['support_replace']);
        unset($entity['total_sales']);
        unset($entity['buy_limit']);
        unset($entity['img']);

        $this->model->startTrans();//基本属性表启动事务
        $error = false;
        $attrModel = new ProductAttrModel();
        $attrModel -> startTrans();//其他属性表启动事务
        $imageModel = M('ProductImage');
        $imageModel -> startTrans();//图片表启动事务
        $propModel = new ProductPropModel();
        $propModel -> startTrans();//prop表启动事务
        $groupModel = new ProductGroupModel();
        $groupModel -> startTrans();//group表启动事务

        $result = $this -> model -> where(array('id' => $id)) -> save($entity);
        if($result === false){
            $error = $this -> model -> getDbError();
            return $this->apiReturnErr($error);
        }

        $result = $attrModel -> where(array('pid' => $id)) -> save($attr_entity);

        if($result === false){
            $this -> model -> rollback();
            $error = $this -> model -> getDbError();
            return $this->apiReturnErr($error);
        }

        $result = $imageModel -> where(array('pid' => $id)) -> delete();

        if($result === false){
            $this -> model -> rollback();
            $attrModel -> rollback();
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $create_time = time();
        $main_img_type = getDatatree('PRODUCT_MAIN_IMG');
        $show_img_type = getDatatree('PRODUCT_SHOW_IMG');
        //向图片表中插入内容
        $main_img = $img['main_img'];
        $img_list = $img['img_list'];
        $i = 0;
        if($main_img!=""){
            $img_entity[$i] = array(
                'pid' => $id,
                'img_id' => $main_img,
                'type' => $main_img_type,
                'create_time' => $create_time,
            );
            $i++;
        }
        if(!is_null($img_list)) {
            foreach ($img_list as $vo) {
                $img_entity[$i] = array(
                    'pid' => $id,
                    'img_id' => $vo,
                    'type' => $show_img_type,
                    'create_time' => $create_time,
                );
                $i++;
            }
        }
        if(is_array($img_entity)){
            if(count($img_entity)==1){
                $img_entity = $img_entity[0];
                $result = $imageModel -> create($img_entity,1);
                if ($result === false) {
                    $error = $imageModel -> getError();
                    $this -> model ->rollback();
                    $attrModel -> rollback();
                    $imageModel -> rollback();
                    return $this -> apiReturnErr($error);
                }
                $result = $imageModel -> add();
            }else {
                $result = $imageModel -> addAll($img_entity);
            }
        }
        if($result === false){
            $this -> model ->rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $error = $imageModel -> getError();
            return $this -> apiReturnErr($error);
        }
        //像prop表中插入数据
        if($properties !== false){
            //先删除原prop表中的属性
            $map = array(
                'pid' => $id,
            );
            $result = $propModel -> where($map) -> delete();
            if($result === false){
                $error = $propModel -> getError();
            }
            if($error === false){
                //删除未出错
                $properties = json_decode($properties,true);
                $data = array();
                foreach($properties as $k => $vo){
                    $map = array(
                        'id' => $vo['vid'],
                    );
                    $result = apiCall(CategoryPropvalueApi::GET_INFO,array($map));
                    if($result['status']){
                        $prop_id = $result['info']['prop_id'];
                        $value_name = $result['info']['valuename'];
                    }else{
                        $error = $result['info'];
                        break;
                    }
                    $entity = array(
                        'pid' => $id,
                        'prop_id' => $prop_id,
                        'value_id' => $vo['vid'],
                        'value_name' => $value_name,
                    );
                    array_push($data,$entity);
                }
                if($error === false){
                    if(is_array($data)){
                        if(count($data)==1){
                            $result = $propModel -> create($data[0],1);
                            if($result !== false){
                                $result = $propModel -> add();
                            }else{
                                $error = $propModel -> getError();
                            }
                        }else{
                            $result = $propModel -> addAll($data);
                        }
                        if($result === false){
                            $error = $propModel -> getError();
                        }
                    }
                }
            }
        }
        if($error === false){
            if($group['product_group'] !== '' && $group['product_group'] !== 0){
                $map = array(
                    'p_id' => $id,
                    //'g_id' => $group['product_group'],
                );
                $result = $groupModel -> where($map) -> delete();
                if($result === false){
                    $error = $groupModel -> getError();
                }

                if($error === false){
                    $entity = array(
                        'start_time' => $group['group_start_time'],
                        'end_time' => $group['group_end_time'],
                        'price' => 0,
                        'p_id' => $id,
                        'g_id' => $group['product_group'],
                    );
                    $result = $groupModel -> create($entity,1);
                    if($result === false){
                        $error = $groupModel -> getError();
                    }else{
                        $result = $groupModel -> add();
                        if($result === false){
                            $error = $groupModel -> getError();
                        }
                    }
                }
            }
        }
        if($error === false){
            $this -> model -> commit();
            $attrModel -> commit();
            $imageModel -> commit();
            $propModel -> commit();
            return $this -> apiReturnSuc($id);
        }else{
            $this -> model -> rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $propModel -> rollback();
            return $this -> apiReturnErr($error);
        }

    }
   /*
    * 简单添加商品信息
    * */
    public function zadd($entity){
        $result = $this -> model -> create($entity, 1);
        if ($result === false) {
            $error = $this -> model -> getError();
            return $this -> apiReturnErr($error);
        } else {
            $result = $this -> model -> add();
            if ($result === false) {
                return $this -> apiReturnErr($this -> model -> getDbError());
            }
            return $this -> apiReturnSuc($result);
        }
    }
    /**
     *
     * 商品添加信息(product,product_attr,product_image)
     * @param $entity
     * @return bool|void
     */
    public function add($entity){

        $attr_entity = array(
            'has_receipt' => $entity['has_receipt'],
            'under_guaranty' => $entity['under_guaranty'],
            'support_replace' => $entity['support_replace'],
            'total_sales' => $entity['total_sales'],
            'buy_limit' => $entity['buy_limit'],
        );
        $img = $entity['img'];//图片
        $properties = $entity['properties'];//prop属性
        $group = $entity['group'];

        unset($entity['has_receipt']);
        unset($entity['under_guaranty']);
        unset($entity['support_replace']);
        unset($entity['total_sales']);
        unset($entity['buy_limit']);
        unset($entity['img']);
        unset($entity['properties']);

        $this->model->startTrans();//基本属性表启动事务
        $error = false;
        $attrModel = new ProductAttrModel();
        $attrModel -> startTrans();//其他属性表启动事务
        $imageModel = new ProductImageModel();
        //$imageModel = M('ProductImage');
        $imageModel -> startTrans();//图片表启动事务
        $propModel = new ProductPropModel();
        $propModel -> startTrans();//prop表启动事务
        $groupModel = new ProductGroupModel();
        $groupModel -> startTrans();//group开启事务
        $result = $this -> model -> create($entity, 1);
        $pid = 0;
        //1. 插入到商品表
        if ($result === false) {
            $error = $this -> model -> getError();
        } else {
            $result = $this -> model -> add();
            if($result === false){
                $error = $this->model->getDbError();
            }else{
                $pid = $result;
            }
        }

        //2. 插入到商品属性表
        if($error === false){
            $attr_entity['pid'] = $pid;
            //2. 前面没出错则插入到商品属性表
            if($attrModel->create($attr_entity,1) === false){
                $error = $attrModel->getError();
            }else{
                $result = $attrModel->add();
                if($result === false){
                    $error = $this->model->getDbError();
                }
            }
        }

        //3. 插入到商品图片表
        if($error === false){
            $create_time = time();
            $main_img_type = getDatatree('PRODUCT_MAIN_IMG');
            $show_img_type = getDatatree('PRODUCT_SHOW_IMG');
            //向图片表中插入内容
            $main_img = $img['main_img'];
            $img_list = $img['img_list'];
            $i = 0;
            if($main_img!=""){
                $img_entity[$i] = array(
                    'pid' => $pid,
                    'img_id' => $main_img,
                    'type' => $main_img_type,
                    'create_time' => $create_time,
                );
                $i++;
            }
            if(!is_null($img_list)){
                foreach($img_list as $vo){
                    $img_entity[$i] = array(
                        'pid' => $pid,
                        'img_id' => $vo,
                        'type' => $show_img_type,
                        'create_time' => $create_time,
                    );
                    $i++;
                }
            }

            if(is_array($img_entity)){
                if(count($img_entity)==1){
                    $img_entity = $img_entity[0];
                    $result = $imageModel -> create($img_entity,1);
                    if($result === false){
                        $error = $imageModel -> getError();
                    }
                    $result = $imageModel -> add();
                }else{
                    $result = $imageModel -> addAll($img_entity);
                }
            }

            if($result === false){
                $error = $this -> Model -> getDbError();
            }

        }else{

            $this->model->rollback();
            return $this->apiReturnErr($error);
        }

        $properties = json_decode($properties,true);
        //4. 插入到prop表
        if($error === false && $properties != false){
            $data = array();
            foreach($properties as $k => $vo){
                $map = array(
                    'id' => $vo['vid'],
                );
                $result = apiCall(CategoryPropvalueApi::GET_INFO,array($map));
                if($result['status']){
                    $prop_id = $result['info']['prop_id'];
                    $value_name = $result['info']['valuename'];
                }else{
                    $error = $result['info'];
                    break;
                }
                $entity = array(
                    'pid' => $pid,
                    'prop_id' => $prop_id,
                    'value_id' => $vo['vid'],
                    'value_name' => $value_name,
                );
                array_push($data,$entity);
            }
            if($error === false){
                if(is_array($data)){
                    if(count($data)==1){
                        $result = $propModel -> create($data[0],1);
                        if($result !== false){
                            $result = $propModel -> add();
                        }else{
                            $error = $propModel -> getError();
                        }
                    }else{
                        $result = $propModel -> addAll($data);
                    }
                    if($result === false){
                        $error = $propModel -> getError();
                    }
                }
            }
        }

        if($group['product_group'] !== '' && $group['product_group'] !== 0){
            $map = array(
                'p_id' => $pid,
                //'g_id' => $group['product_group'],
            );
            $result = $groupModel -> where($map) -> delete();
            if($result === false){
                $error = $groupModel -> getError();
            }

            if($error === false){
                $entity = array(
                    'start_time' => $group['group_start_time'],
                    'end_time' => $group['group_end_time'],
                    'price' => 1000,
                    'ori_price'=>1000,
                    'p_id' => $pid,
                    'g_id' => $group['product_group'],
                );
                $result = $groupModel -> create($entity,1);
                if($result === false){
                    $error = $groupModel -> getError();
                }else{
                    $result = $groupModel -> add();
                    if($result === false){
                        $error = $groupModel -> getError();
                    }
                }
            }
        }

        if($error !==false){
            $this -> model -> rollback();
            $attrModel -> rollback();
            $imageModel -> rollback();
            $propModel -> rollback();
            $groupModel -> rollback();
            return $this -> apiReturnErr($error);
        }else{
            $this -> model -> commit();
            $attrModel -> commit();
            $imageModel -> commit();
            $propModel -> commit();
            $groupModel -> commit();
            return $this -> apiReturnSuc($pid);
        }


    }

    /**
     *
     * @param int $uid
     * @param null $map
     * @param array $page
     * @param bool $order
     * @param bool $params
     * @param bool $fields
     * @return array
     */
	public function queryWithStoreUID($uid=0,$map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){
		$query = $this->model;
		
		$result = $query->query("select * from __STORE__ where uid = $uid");
		
		if($result === false){
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}
		$storeidlist = array('0');
		foreach($result as $store){
			array_push($storeidlist,($store['id']));
		}
		
		$_map['storeid'] = array('in',$storeidlist);
		
		$map = array_merge($_map,$map);
		
		if(!is_null($map)){
			$query = $query->where($map);
		}
		
		if(!($order === false)){
			$query = $query->order($order);
		}
		if(!($fields === false)){
			$query = $query->field($fields);
		}

		$list = $query -> page($page['curpage'] . ',' . $page['size'])  -> select();
		

		if ($list === false) {
			$error = $this -> model -> getDbError();
			return $this -> apiReturnErr($error);
		}

		$count = $this -> model -> where($map) -> count();
		// 查询满足要求的总记录数
		$Page = new Page($count, $page['size']);

		//分页跳转的时候保证查询条件
		if ($params !== false) {
			foreach ($params as $key => $val) {
				$Page -> parameter[$key] = urlencode($val);
			}
		}

		// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page -> show();

		return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
	}

    /**
     * @param $name
     * @param $type
     * @param $page
     * @param $order
     * @param $params
     * @return array
     */
    public function queryWithStore($name,$type,$page,$order,$params){


        $query = $this->model;//->field("")->alias(" pd ")->join("LEFT JOIN __WXSTORE__ as st on st.id = pd.storeid ");

        $sql = "select  pd.name as name ,pd.id,pd.main_img,pd.buy_limit,pd.attrext_ispostfree,pd.attrext_ishasreceipt,pd.attrext_issupportreplace,pd.loc_country,pd.loc_province,pd.loc_city,pd.loc_address,pd.has_sku,pd.ori_price,pd.price,pd.quantity,pd.product_code,pd.cate_id,
		pd.createtime,pd.updatetime,pd.onshelf,pd.status,pd.storeid,pd.properties,pd.sku_info,pd.detail,st.uid,st.name as storename,st.desc,st.isopen,st.logo,st.banner,st.wxno,st.exp";
        $sql .= " from __PRODUCT__ as pd LEFT JOIN __STORE__ as st on st.id = pd.storeid  ";
        if($type == '1'){
            $whereName = " pd.name ";
        }else{
            $whereName = "st.name";
        }
        $sql .= " where pd.onshelf = ".ProductModel::STATUS_ONSHELF;
        if(!empty($name)){
            $sql .= " and  $whereName like '%".$name."%' ";
        }

        $sql .= ' order by '. $order;
//		if(!($order === false)){
//			$query = $query->order($order);
//		}
        $sql .= " LIMIT ".(intval($page['curpage'])*$page['size']) . ',' . $page['size'];

        $list = $query->query($sql);


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $countSql = " select count(*) as cnt from __PRODUCT__ as pd LEFT JOIN __STORE__ as st on st.id = pd.storeid   ";
        if(!empty($name)){
            $countSql .= " where $whereName like '%".$name."%'";
        }

        $count = $query->query($countSql);
        $count = $count[0]['cnt'];
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        // 分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

    /**
     * @param $group_id
     * @param $map
     * @param $page
     * @return array
     */
    public function queryByGroup($group_id,$map,$page){
        $result = $this->model->query("select g_id,p_id from __PRODUCT_GROUP__ where `g_id` = ".$group_id);
        if($result === FALSE){
            return $this->apiReturnErr($this->model->getDbError());
        }
        $product_ids = array(-1);

        foreach($result as $vo){
            array_push($product_ids,$vo['p_id']);
        }

        if(is_null($map)){
            $map = array();
        }

        $map['id'] = array('in',$product_ids);
        $map['status'] = 1;
        $map['onshelf'] = ProductModel::STATUS_ONSHELF;

        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        // 分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

    public function queryWithCountJoinCate($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $query = $this->model;

        $main_img_type = 6015;//主图

        $query = $query->alias('p') -> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on p.id=image.pid','left') -> join('(select min(price) as price,product_id from itboye_product_sku group by product_id) as sku on p.id=sku.product_id','inner') -> join('itboye_product_attr on p.id=itboye_product_attr.pid','left')
        ->join('__CATEGORY__ as c on p.cate_id = c.id','left');

        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model->alias('p')-> join('(select img_id as img,pid from itboye_product_image where type='.$main_img_type.') as image on id=image.pid','left') -> join('(select min(price) as price,product_id from itboye_product_sku group by product_id) as sku on p.id=sku.product_id','inner') -> join('itboye_product_attr on p.id=itboye_product_attr.pid','left')->join('__CATEGORY__ as c on p.cate_id = c.id','left') -> where($map) -> count();

        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        $show = $Page -> show();


        return $this -> apiReturnSuc(array("count" => $count, "list" => $list));
    }

    /*
 * 查询出卖家卖出的所有商品
 * */
    public function selectSellOrder($map,$field = false){
        $query = $this->model->where($map);
        $result = $query->alias('a')->join("RIGHT JOIN itboye_orders_item i on a.id = i.p_id")->join('LEFT JOIN itboye_orders o on i.order_code = o.order_code')->field($field)->order('o.createtime desc')->select();
        if ($result === FALSE) {
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        } else {
            return $this->apiReturnSuc($result);
        }
    }

    /*
     * 分页调出所有商品信息因为API的相应方法被重写了 所以需要在这里重新定义
     * */
    public function page_all_product($map = null, $limit = array('curpage'=>0,'size'=>20), $order = false, $fields = false) {
        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $start = ($limit['curpage']-1)*$limit['size'];
        $list = $query ->limit($start,$limit['size']) -> select();
        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        return $this -> apiReturnSuc($list);
    }

    /*
     * 连表查询将发布商品的用户信息和商品一起查出
     * */
    public function product_wxuser($map,$page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){
        $query = $this->model->join('INNER JOIN itboye_wxuser on itboye_wxuser.id = itboye_product.uid');
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }
}

